package com.ict.web.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.web.domain.ExtractExpert;
import com.ict.web.domain.ExtractMonitoring;
import com.ict.web.domain.ReviewTask;
import com.ict.web.dto.ExtractMonitoringAllDto;
import com.ict.web.dto.ExtractMonitoringDto;
import com.ict.web.dto.ExtractMonitoringRuleDto;
import com.ict.web.dto.QueryExpertExtractMonitorDto;
import com.ict.web.mapper.ExtractMonitoringMapper;
import com.ict.web.service.ExtractMonitoringService;
import com.ict.web.service.IExtractExpertService;
import com.ict.web.service.IReviewTaskService;
import com.ict.web.vo.ExpertExtractionMonitorListVo;
import com.ict.web.vo.ExtractRuleBeginVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽取监控Service业务层处理
 *
 * @author xc
 * @date 2022-04-27
 */
@Service
public class ExtractMonitoringServiceImpl extends ServiceImpl<ExtractMonitoringMapper, ExtractMonitoring> implements ExtractMonitoringService
{
    @Autowired
    private ExtractMonitoringMapper extractMonitoringMapper;
    @Autowired
    private IReviewTaskService reviewTaskService;
    @Autowired
    private IExtractExpertService extractExpertService;

    @Override
    public List<ExpertExtractionMonitorListVo> list(QueryExpertExtractMonitorDto dto) {
        return extractMonitoringMapper.list(dto);
    }

    @Override
    public int add(ExtractMonitoringAllDto dto) {
        ExtractMonitoringDto monitoringDto = dto.getMonitoringDto();
        //新增评审任务时生成抽取监控
        String extractFrequency=null;
        if(StringUtils.isNull(monitoringDto.getReviewTaskId())){
            List<ExtractMonitoring> planArrayList = new ArrayList<>();
            //年度抽取
            if(StringUtils.isNotNull(monitoringDto.getPlanId())){
                List<ExtractMonitoring> planList = extractMonitoringMapper.selectList(
                        new QueryWrapper<ExtractMonitoring>().eq("plan_id", monitoringDto.getPlanId()));
                planArrayList.addAll(planList);
            }
            //项目抽取
            if(StringUtils.isNotNull(monitoringDto.getProId())){
                List<ExtractMonitoring> proList = extractMonitoringMapper.selectList(
                        new QueryWrapper<ExtractMonitoring>().eq("pro_id", monitoringDto.getProId()));
                planArrayList.addAll(proList);
            }
            switch (planArrayList.size()) {
                case 0:
                    extractFrequency="1";
                    break;
                case 1:
                    extractFrequency="2";
                    break;
                case 2:
                    extractFrequency="3";
                    break;
                default:
                    Assert.isTrue(false,"抽取次数已完，请提交");
                    break;
            }
            String expertInformation = JSON.toJSONString(dto.getExpertDto());
            String ruleInformation = JSON.toJSONString(dto.getRuleDto());
            ExtractMonitoring monitoring = new ExtractMonitoring(IdUtils.snowId(),monitoringDto.getProId(),monitoringDto.getPlanId(),null,null,ruleInformation,expertInformation,
                    LocalDateTime.now(),extractFrequency,monitoringDto.getExtractType(),monitoringDto.getExtractResult(), String.valueOf(SecurityUtils.getDeptId()),SecurityUtils.getNickName(),monitoringDto.getExtractNum(), ExtractExpert.DELETE_STATUS_NORMAL,null);
            return extractMonitoringMapper.insert(monitoring);
            //更换专家生成抽取监控
        }else {
            ExtractMonitoringDto monitoringDto1 = dto.getMonitoringDto();
            Assert.isTrue(StringUtils.isNotNull(monitoringDto1.getReviewTaskId()),"更换专家生成抽取监控：评审任务id不能为空");
            ReviewTask reviewTask = reviewTaskService.getById(monitoringDto1.getReviewTaskId());
            Assert.isTrue(StringUtils.isNotNull(reviewTask),"更换专家生成抽取监控：未找到该评审任务");
            //抽取监控增加评审任务信息
            List<ExtractMonitoring> extractMonitoringList = extractMonitoringMapper.selectList(new QueryWrapper<ExtractMonitoring>()
                    .eq("review_task_id", reviewTask.getReviewTaskId())
                    .eq("extract_expert_id", monitoringDto1.getExtractExpertId())
                    .isNull("task_name")
                    .orderByDesc("extract_time"));
            Integer size = extractMonitoringList.size();
            int integer = extractMonitoringMapper.updateById(extractMonitoringList.get(0).setExtractResult(ExtractMonitoring.EXTRACT_RESULT_SEND));
            String exchangeType = monitoringDto1.getExchangeType();
            //重复更换次数为3时，重新更换为2次
            Long extractExpertId = monitoringDto1.getExtractExpertId();
            ExtractExpert extractExpert = extractExpertService.getById(extractExpertId);
            if(extractExpert.getAgainExtractNum().equals("3")){
                exchangeType="2";
                //重新抽取次数用完初始化
                extractExpert.setAgainExtractNum("0");
                extractExpertService.updateById(extractExpert);
            }
            for (int i = 0; i <=Integer.parseInt(exchangeType); i++) {
                ExtractMonitoring extractMonitoring = extractMonitoringList.get(i);
                extractMonitoring.setTaskName(reviewTask.getTaskName());
                extractMonitoringMapper.updateById(extractMonitoring);
            }
            return integer;
        }
    }

    @Override
    public ExtractMonitoringAllDto getExpertInfo(Long planId, Long proId) {
        List<ExtractMonitoring> list = new ArrayList<>();
        //年度抽取
        if(StringUtils.isNotNull(planId)){
            List<ExtractMonitoring> planList = extractMonitoringMapper.selectList(
                    new QueryWrapper<ExtractMonitoring>().eq("plan_id", planId).orderByDesc("extract_time"));
            list.addAll(planList);
        }
        //项目抽取
        if(StringUtils.isNotNull(proId)){
            List<ExtractMonitoring> proList = extractMonitoringMapper.selectList(
                    new QueryWrapper<ExtractMonitoring>().eq("pro_id", proId).orderByDesc("extract_time"));
            list.addAll(proList);
        }
        if(StringUtils.isEmpty(list)){
            return null;
        }
        ExtractMonitoring extractMonitoring = list.get(0);
        //解析规则信息和专家信息
        String expertInformation = extractMonitoring.getExpertInformation();
        String ruleInformation = extractMonitoring.getRuleInformation();
        List<ExtractRuleBeginVo> extractRuleBeginVoList = JSON.parseArray(expertInformation, ExtractRuleBeginVo.class);
        List<ExtractMonitoringRuleDto> extractMonitoringRuleDtoList = JSON.parseArray(ruleInformation, ExtractMonitoringRuleDto.class);
        ExtractMonitoringAllDto extractMonitoringAllDto = new ExtractMonitoringAllDto();
        extractMonitoringAllDto.setExpertDto(extractRuleBeginVoList);
        extractMonitoringAllDto.setRuleDto(extractMonitoringRuleDtoList);
        ExtractMonitoringDto extractMonitoringDto = new ExtractMonitoringDto();
        BeanUtils.copyProperties(extractMonitoring,extractMonitoringDto);
        extractMonitoringDto.setExchangeType(extractMonitoring.getExtractFrequency());
        extractMonitoringAllDto.setMonitoringDto(extractMonitoringDto);
        return extractMonitoringAllDto;
    }
}
